import router, { doRoutes } from './router'
// import store from './store'
// import { Message } from 'element-ui'
// 导入进度条
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import store from './store'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // console.log('从哪里来', from)
  // console.log('到哪里去', to)
  // 进度条开始时
  NProgress.start()

  // 页面标题
  document.title = getPageTitle(to.meta.title)

  // 获取token
  const hasToken = getToken()
  if (!hasToken) {
    if (!whiteList.includes(to.path)) {
      // 跳转登录页
      next('/login')// 如果next 指定的地址就不会经过afterEach
      // 进度条结束
      return NProgress.done()
    }
    next()
    return
  }
  if (to.path === '/login') {
    next('/')
    return NProgress.done()
  }
  // 获取用户信息
  // console.log(store.getters.userId)
  if (!store.getters.userId) {
    const menus = await store.dispatch('user/getInfo')
    console.log(menus, 'menus')
    const asyncRouter = doRoutes.filter(item => menus.includes(item.children[0].name))
    console.log('asyncRouter', asyncRouter)
    router.addRoutes(asyncRouter)
    router.addRoutes([
      {
        path: '*',
        redirect: '/404',
        hidden: true
      }
    ])
    store.commit('menu/setAsyncRouter', asyncRouter)
    return next({ ...to, replace: true })
  }
  next()
})

router.afterEach(() => {
  // 进度条结束
  NProgress.done()
})
